/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2024 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "adc.h"
#include "dma.h"
#include "fdcan.h"
#include "spi.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */

#include "stdio.h"
#include <stdlib.h>
#include "string.h"

int new_t=0;
int tp1=0;
int tp2=0;
int tp3=0;
int tp4=0;
int tp[4]={0};
int mode_charge = 0;

//#define nor_flash_start_address 0x00000  //外部flash起始地址

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
  uint32_t adc_value[100];
	uint32_t adc_value_make[100];
	uint32_t medium_value[100];
	float result_temp[8];

uint8_t channel_index = 0;
uint16_t adc_buffer[8];
//	float adc_temp[8];
//	int32_t result_pt[8];
//	float Rx;
//	float result_1[8];
/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
void PeriphCommonClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

float calculate_average(uint32_t data[], int count) {	 
    // 查找最大和最小值的索引
    int max_index = 0;
    int min_index = 0;
    int sum = 0;
    for (int i = 1; i < count; ++i) {
        if (data[i] > data[max_index]) {
            max_index = i;
        }

        if (data[i] < data[min_index]) {
            min_index = i;
        }
    }

    // 计算总和   
    for (int i = 0; i < count; ++i) {
        sum += data[i];
    }
		    
		// 去除最大和最小值
    sum -= data[max_index];
    sum -= data[min_index];		

    // 计算平均值
    uint32_t average = (uint32_t)(sum / (count-2));
		
    return average;
}

//阻值对应温度
float PT100_to_temperature(float Rt) {
	  if(Rt<18.52){
			Rt = 18.52;
		}
    const float A = 3.9083e-3;
    const float B = -5.775e-7;
    const float C = -4.183e-12;
    const float R0 = 100.0;
    float t_guess = 0.0;
    float t_min = -200.0;  // 假设温度范围为 -200°C 到 850°C
    float t_max = 850.0;
    float Rt_guess = 0.0;
    const float epsilon = 0.01; // 迭代精度

    // 使用二分查找方法来寻找对应的温度
    while (fabs(t_max - t_min) > epsilon) {
        t_guess = (t_min + t_max) / 2;
        if (t_guess >= 0) {
            Rt_guess = R0 * (1 + A * t_guess + B * t_guess * t_guess);
        } else {
            Rt_guess = R0 * (1 + A * t_guess + B * t_guess * t_guess + C *(t_guess-100)* t_guess * t_guess * t_guess);
        }
        if (Rt_guess < Rt) {
            t_min = t_guess;
        } else {
            t_max = t_guess;
        }
    }
		//补偿
     t_guess=t_guess-0.2;
		if(t_guess<-200.0){
			t_guess=-200.0;
		}
		if(t_guess>849.6){
			t_guess=850.0;
		}
    // 返回找到的温度
    return t_guess;
}

uint8_t Write_To_NorFlash2(uint8_t data,uint32_t address) {
	 		  
    W25Q16_Page_Program(&data, address, sizeof(data));
						
		return 1;
}

//惠斯通电桥计算
float PT100_calculate(uint32_t adc){
	    float adc_temp = (adc * 3.3 / 65535) /10;
			float Rx = (15*2550 + 2550*2565*adc_temp/2.5)/(2550-2565*adc_temp/2.5);
      int32_t result_pt = (int32_t)(PT100_to_temperature(Rx)*10);
		  float result_1 = result_pt/10.0;
	    return result_1;
}

//切换通道
void switch_cd4052_channel(uint8_t channel) {
    switch(channel) {
        case 0:
			      HAL_GPIO_WritePin(MU_B_GPIO_Port, MU_B_Pin, GPIO_PIN_RESET);
	          HAL_GPIO_WritePin(MU_A_GPIO_Port, MU_A_Pin, GPIO_PIN_SET);
            break;
        case 1:
			      HAL_GPIO_WritePin(MU_B_GPIO_Port, MU_B_Pin, GPIO_PIN_SET);
	          HAL_GPIO_WritePin(MU_A_GPIO_Port, MU_A_Pin, GPIO_PIN_RESET);
            break;
        case 2:
			      HAL_GPIO_WritePin(MU_B_GPIO_Port, MU_B_Pin, GPIO_PIN_SET);
	          HAL_GPIO_WritePin(MU_A_GPIO_Port, MU_A_Pin, GPIO_PIN_SET);
            break;
        case 3:
			      HAL_GPIO_WritePin(MU_B_GPIO_Port, MU_B_Pin, GPIO_PIN_RESET);
	          HAL_GPIO_WritePin(MU_A_GPIO_Port, MU_A_Pin, GPIO_PIN_RESET);
            break;
        default:
            // 处理错误或其他情况
            break;
    }
    // 等待一段时间，确保有足够的时间来完成通道切换
		HAL_Delay(1);
}


/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

/* Configure the peripherals common clocks */
  PeriphCommonClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_ADC1_Init();
  MX_FDCAN1_Init();
  MX_SPI3_Init();
  /* USER CODE BEGIN 2 */
	
	//A1低平，A0高平，放大增益10
////	HAL_GPIO_WritePin(GAIN_A1_GPIO_Port, GAIN_A1_Pin, GPIO_PIN_SET);
	HAL_GPIO_WritePin(GAIN_A0_GPIO_Port, GAIN_A0_Pin, GPIO_PIN_SET);

	//第1路
	HAL_GPIO_WritePin(MU_B_GPIO_Port, MU_B_Pin, GPIO_PIN_RESET);
	HAL_GPIO_WritePin(MU_A_GPIO_Port, MU_A_Pin, GPIO_PIN_RESET);
	//1-4路开
	HAL_GPIO_WritePin(MU1_EN_GPIO_Port, MU1_EN_Pin, GPIO_PIN_RESET);//默认低电平，置高时采样结束
	
  HAL_ADCEx_Calibration_Start(&hadc1,ADC_CALIB_OFFSET,ADC_SINGLE_ENDED); //ADC校准	
	HAL_Delay(10);
	
	HAL_ADC_Start_DMA(&hadc1, (uint32_t *)adc_value, 1);
	HAL_Delay(10);
			
			uint8_t id_now[4];
			W25Q16_Read(&id_now[0], nor_flash_start_address, 1);
			W25Q16_Read(&id_now[1], nor_flash_start_address+1, 1);
			
			W25Q16_Read(&id_now[2], nor_flash_start_address+2, 1);
			W25Q16_Read(&id_now[3], nor_flash_start_address+3, 1);
			
			id_new_spi[0] = id_now[0]+id_now[1]*256;
			id_new_spi[1] = id_now[2]+id_now[3]*256;
      
			if(id_new_spi[0]==0||id_new_spi[1]==0){
				id_new_spi[0] = 0x100;
				id_new_spi[1] = 0x101;			
			}
			
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {   						
		if(mode_charge==0){
			 uint8_t sendData1[4];
			 sendData1[0] = id_new_spi[0] & 0xFF;          
			 sendData1[1] = (id_new_spi[0] >> 8) & 0xFF;  
			 sendData1[2] = id_new_spi[1] & 0xFF;          // id_new1 的低位
			 sendData1[3] = (id_new_spi[1] >> 8) & 0xFF;   // id_new1 的高位		 
															 
			 can_SendPacket(0x2,sendData1,4);
			
			if(new_t<12){
				medium_value[new_t] = adc_value[0];
				new_t++;
			}
			
			if(new_t==12){
			new_t=0;	
			//滤波
			adc_value_make[0] = calculate_average(medium_value, 12);
			adc_buffer[channel_index] = adc_value_make[0];
		
    if (channel_index >= 3) {
      // 如果已经采集完四个通道，则发送数据到CAN总线
			result_temp[0] =  PT100_calculate(adc_buffer[0]);
      result_temp[1] =	PT100_calculate(adc_buffer[1]);	
			result_temp[2] =  PT100_calculate(adc_buffer[2]);
      result_temp[3] =	PT100_calculate(adc_buffer[3]);
															
			uint8_t txdata12[8];
			uint8_t txdata34[8];

			memcpy(txdata12, &result_temp[0], 4);
			memcpy(txdata12 + 4, &result_temp[1], 4);
			memcpy(txdata34, &result_temp[2], 4);
			memcpy(txdata34 + 4, &result_temp[3], 4);
			
      can_SendPacket(id_new_spi[0],txdata12,8);
			can_SendPacket(id_new_spi[1],txdata34,8);
			
			switch_cd4052_channel(channel_index);
									
        // 重置通道索引
        channel_index = -1;
    } 
		else {
        // 否则切换到下一个通道
        switch_cd4052_channel(channel_index);
    }
       channel_index++;

			 HAL_Delay(20);
	   }
			HAL_Delay(1);
		 
		}
		else if(mode_charge==1){
		  		
		HAL_Delay(30);
			
		}
		
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Supply configuration update enable
  */
  HAL_PWREx_ConfigSupply(PWR_LDO_SUPPLY);

  /** Configure the main internal regulator output voltage
  */
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);

  while(!__HAL_PWR_GET_FLAG(PWR_FLAG_VOSRDY)) {}

  __HAL_RCC_SYSCFG_CLK_ENABLE();
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE0);

  while(!__HAL_PWR_GET_FLAG(PWR_FLAG_VOSRDY)) {}

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_DIV1;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
  RCC_OscInitStruct.PLL.PLLM = 4;
  RCC_OscInitStruct.PLL.PLLN = 60;
  RCC_OscInitStruct.PLL.PLLP = 2;
  RCC_OscInitStruct.PLL.PLLQ = 12;
  RCC_OscInitStruct.PLL.PLLR = 2;
  RCC_OscInitStruct.PLL.PLLRGE = RCC_PLL1VCIRANGE_3;
  RCC_OscInitStruct.PLL.PLLVCOSEL = RCC_PLL1VCOWIDE;
  RCC_OscInitStruct.PLL.PLLFRACN = 0;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2
                              |RCC_CLOCKTYPE_D3PCLK1|RCC_CLOCKTYPE_D1PCLK1;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.SYSCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB3CLKDivider = RCC_APB3_DIV2;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_APB1_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_APB2_DIV2;
  RCC_ClkInitStruct.APB4CLKDivider = RCC_APB4_DIV2;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK)
  {
    Error_Handler();
  }
}

/**
  * @brief Peripherals Common Clock Configuration
  * @retval None
  */
void PeriphCommonClock_Config(void)
{
  RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0};

  /** Initializes the peripherals clock
  */
  PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_CKPER;
  PeriphClkInitStruct.CkperClockSelection = RCC_CLKPSOURCE_HSI;
  if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
